//% color="#1E90FF" iconWidth=50 iconHeight=40
namespace DeepseekAI {

    //% block="初始化Deepseek [Base_url] API密钥:[API] 定义角色:[Deepseek_system] 温度:[TEMPERATURE]" blockType="command"
    //% API.shadow="string" API.defl="YOUR_API"
    //% Base_url.shadow="dropdown" Base_url.options="base_url"
     //% Deepseek_system.shadow="string" Deepseek_system.defl="你是 Deepseek，人工智能助手,你更擅长中文对话。"
    //% TEMPERATURE.shadow="range" TEMPERATURE.params.max=200 TEMPERATURE.params.min=1 TEMPERATURE.defl="30"
    export function initializeMoonshotAI(parameter: any, block: any) {
        let Deepseek_api = parameter.API.code;
        let Base_url = parameter.Base_url.code;
        let  Deepseek_system = parameter. Deepseek_system.code;
        let temperature = parameter.TEMPERATURE.code/100;
        Generator.addImport(`import openai\nimport json`);
        if(Base_url=="https://api.deepseek.com"){
         let Deepseek_model="deepseek-chat";
          }
         else{
          let Deepseek_model="deepseek-ai/DeepSeek-V3";
         }
        Generator.addCode(`
client = openai.OpenAI(api_key=${Deepseek_api}, base_url="${Base_url}")
Deepseek_model ="${Deepseek_model}"
Deepseek_temperature = ${temperature}
Deepseek_history = [
    {"role": "system", "content": ${Deepseek_system}}
]

def Deepseek_chat(query, Deepseek_history, Deepseek_model, Deepseek_temperature):
    Deepseek_history.append({
        "role": "user", 
        "content": query
    })
    completion = client.chat.completions.create(
        model=Deepseek_model,
        messages=Deepseek_history,
        temperature=Deepseek_temperature,
    )
    result = completion.choices[0].message.content
    Deepseek_history.append({
        "role": "assistant",
        "content": result
    })
    return result
`);
    }

    //% block="发送消息 [MESSAGE] 并返回响应" blockType="reporter"
    //% MESSAGE.shadow="string" MESSAGE.defl="你好，AI"
    export function sendMessage(parameter: any, block: any) {
        let message = parameter.MESSAGE.code;

        Generator.addCode(`Deepseek_chat(${message},Deepseek_history, Deepseek_model, Deepseek_temperature)`);
    }

}
